package com.javaweb.controller;

import com.javaweb.entity.Result;
import com.javaweb.utils.AliOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliOSSUtil aliOSSUtils;

    //使用云存储服务（阿里云）
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        String originalFilename = image.getOriginalFilename();
        log.info("上传文件。文件名：{}", originalFilename);

        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //只接受图片类型
        if (!".jpg".equals(suffix) && !".jpeg".equals(suffix) && !".png".equals(suffix)){
            log.info("上传失败。文件格式不合法");
            return Result.error("文件格式不合法");
        }
        //上传文件
        String url = aliOSSUtils.upload(image);
        log.info("上传成功。文件访问的url：{}", url);
        return Result.success(url);
    }
}
